package com.huatai.common.util;

import com.huatai.common.constant.ChineseName;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtil<T> {
	private final Class<T> clazz;

	public ExcelUtil(Class<T> clazz) {
		this.clazz = clazz;
	}


	/**
	 * 导出Excel文件
	 *
	 * @param response  HttpServletResponse
	 * @param list      数据列表
	 * @param sheetName 工作表名称
	 */
	public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) {
		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet(sheetName);

		// 创建标题行
		Row titleRow = sheet.createRow(0);
		Field[] fields = clazz.getDeclaredFields();
		// 计算带ChineseName注解的字段数量，以便知道标题行需要多少单元格
		int annotatedFieldsCount = 0;
		for (Field field : fields) {
			if (field.isAnnotationPresent(ChineseName.class)) {
				annotatedFieldsCount++;
			}
		}
		// 初始化列索引
		int index = 0;
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if (field.isAnnotationPresent(ChineseName.class)) {
				ChineseName annotation = field.getAnnotation(ChineseName.class);
				String chineseName = annotation.value();
				Cell cell = titleRow.createCell(index);
				cell.setCellValue(chineseName);
				index++;
			}
		}

		// 填充数据
		for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) {
			T item = list.get(rowIndex);
			Row row = sheet.createRow(rowIndex + 1);
			int columnIndex = 0; // 初始化列索引
			for (Field field : fields) {
				if (field.isAnnotationPresent(ChineseName.class)) { // 检查是否带有ChineseName注解
					field.setAccessible(true);
					Cell cell = row.createCell(columnIndex++);
					try {
						Object value = field.get(item);
						if (value instanceof Date) { // 如果是日期，格式化
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							cell.setCellValue(sdf.format(value));
						} else {
							cell.setCellValue(value != null ? value.toString() : "");
						}
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}

		// 设置响应头
		response.setContentType("application/octet-stream");
		String fileName = sheetName + ".xlsx";
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

		// 写入响应
		try (OutputStream out = response.getOutputStream()) {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 关闭Workbook
		try {
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
